package common

import com.redis.{RedisClient, RedisClientPool}

import com.typesafe.config.ConfigFactory

import scala.concurrent.Future

object JedisTool {
  lazy val conf = ConfigFactory.load()
  lazy private val pool: RedisClientPool = {
    val host= conf.getString("redis.host")
    println("init redis :" + host)
      val ipport = host.split(";")(0)
      val jsi =
      if (host.split(";").size > 1) {
        new RedisClientPool(ipport.split(":")(0), ipport
          .split(":")(1).toInt,maxIdle = 60,secret = Some(host.split(";")(1)))
      }else{
        new RedisClientPool(ipport.split(":")(0), ipport
          .split(":")(1).toInt,maxIdle = 60)
      }
      jsi.withClient { c => println(host + "=" + c.ping) }
      jsi
  }

  def useJedis[T](body: RedisClient => T) = {
        pool.withClient{c=>
          body(c)
        }
  }
  def getJedis=pool.pool.borrowObject()

  def disconnect() {
    try {
      pool.close
    } catch {
      case e: Exception =>
        e.printStackTrace()
    }

  }
}
